#include <iostream>
#include <cstring>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

static const int defaultsockfd = -1;
static const int defaultmaxretries = 5;
static const int defaultretryinterval = 1;

enum ExitCode
{
    USAGE_ERR = 1,
    SOCKET_ERR
};

enum class Status // C++11强制类型检查
{
    NEW,
    CONNECTING,
    CONNECTED,
    DISCONNECTED,
    CLOSED
};

// 状态机
class ClientConnection
{
public:
    ClientConnection(const std::string &serverip, uint16_t serverport)
        : _status(Status::NEW), _sockfd(defaultsockfd), _serverip(serverip), _serverport(serverport), _max_retries(defaultmaxretries), _retry_interval(defaultretryinterval)
    {
    }
    void Connect()
    {
        // 1. 创建套接字
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd < 0)
        {
            std::cerr << "socket error" << std::endl;
            exit(ExitCode::SOCKET_ERR);
        }
        // 2. 客户端不需要bind, OS会自动绑定
        // 2. 构建目标服务器
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(_serverport);
        inet_pton(AF_INET, _serverip.c_str(), &server.sin_addr); // 字符串转4字节网络序
        // 3. 直接进行connect
        int n = connect(_sockfd, (struct sockaddr *)&server, sizeof(server)); // 自动进行bind哦!
        if (n < 0)
        {
            // 连接失败，关闭套接字，进行重连
            Disconnect();
            _status = Status::DISCONNECTED;
            return;
        }
        // 连接成功
        _status = Status::CONNECTED;
        std::cout << "连接成功" << std::endl;
    }
    // 连接成功了，就进行正常的IO通信
    void Process()
    {
        while (true)
        {
            std::string inbuffer;
            std::cout << "Please Enter# ";
            std::getline(std::cin, inbuffer);
            if (inbuffer.empty())
                continue;
            int n = send(_sockfd, inbuffer.c_str(), inbuffer.size(), 0);
            if (n > 0)
            {
                char buffer[1024];
                int m = recv(_sockfd, buffer, sizeof(buffer) - 1, 0);
                if (m > 0)
                {
                    buffer[m] = 0;
                    std::cout << "server echo: " << buffer << std::endl;
                }
                else if (m == 0)
                {
                    // server 断线了
                    _status = Status::DISCONNECTED;
                    break;
                }
                else
                {
                    std::cout << "recv m: " << m << "errno: " << errno << "error string: " << strerror(errno) << std::endl;
                    _status = Status::CLOSED;
                    break;
                }
            }
            else
            {
                std::cout << "send n: " << n << "errno: " << errno << "error string: " << strerror(errno) << std::endl;
                _status = Status::CLOSED;
                break;
            }
        }
    }
    // 连接失败，或者server断线，进行重连
    void Reconnect()
    {
        _status = Status::CONNECTING; // 正在进行重连
        int cnt = 0;
        while (true)
        {
            Connect();
            if (_status == Status::CONNECTED)
                break;
            cnt++;
            std::cout << "重连次数: " << cnt << std::endl;
            sleep(_retry_interval);
            if (cnt >= _max_retries)
            {
                std::cout << "重连失败，请检查网络状态!" << std::endl;
                _status = Status::CLOSED;
                break;
            }
        }
    }
    // 重连都失败，关闭套接字，退出
    void Disconnect()
    {
        if (_sockfd != defaultsockfd)
        {
            close(_sockfd);
            _sockfd = defaultsockfd;
            _status = Status::CLOSED;
        }
    }
    // 获取状态
    Status GetStatus()
    {
        return _status;
    }
    ~ClientConnection()
    {
        Disconnect();
    }

private:
    Status _status; // 连接状态
    int _sockfd;    // 套接字
    std::string _serverip;
    uint16_t _serverport;
    int _max_retries;    // 最多重连次数
    int _retry_interval; // 重连的时间间隔
};

// 客户端对象
class TcpClient
{
public:
    TcpClient(const std::string &serverip, uint16_t serverport)
        : _conn(serverip, serverport)
    {
    }
    void Excute()
    {
        while (true)
        {
            switch (_conn.GetStatus())
            {
            case Status::NEW:
                _conn.Connect();
                break;
            case Status::CONNECTED:
                _conn.Process();
                break;
            case Status::DISCONNECTED:
                _conn.Reconnect();
                break;
            case Status::CLOSED:
                _conn.Disconnect();
                return; // 结束了
            default:
                break;
            }
        }
    }
    ~TcpClient()
    {
    }

private:
    ClientConnection _conn;
};

void Usage(const std::string &process)
{
    std::cout << "Usage: " << process << " serverip" << " serverport" << std::endl;
}

// tcpclient serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(ExitCode::USAGE_ERR);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    TcpClient tcpclient(serverip, serverport);
    tcpclient.Excute();
    return 0;
}